<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :keyboard="false"
    :forceRender="true"
    v-bind:prefixNo="prefixNo"
    fullscreen
    switchFullscreen
    @cancel="handleCancel"
    :id="prefixNo"
    style="top: 20px; height: 95%"
  >
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" :loading="confirmLoading" @click="handleOk">保存（Ctrl+S）</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="供应商">
              <a-select
                placeholder="请选择供应商"
                v-decorator="['supplierId', validatorRules.supplierId]"
                :disabled="!rowCanEdit"
                :dropdownMatchSelectWidth="false"
                showSearch
                optionFilterProp="children"
              >
                <a-select-option v-for="(item, index) in supList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
           <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="业务人员"
              data-step="3"
              data-title="业务人员"
            >
              <a-select
                placeholder="请选择业务人员"
                showSearch
                optionFilterProp="children"
                v-decorator="['salespersonId', validatorRules.salespersonId]"
              >
                <a-select-option v-for="(item, index) in userList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="单据日期">
              <j-date v-decorator="['operTime', validatorRules.operTime]" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="单据编号">
              <a-input placeholder="请输入单据编号" v-decorator.trim="['orderNo']" />
            </a-form-item>
          </a-col>
         
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="业务类型">
              <a-select
                placeholder="请选择业务类型"
                v-decorator="['businessType', validatorRules.type]"
                optionFilterProp="children"
              >
                <a-select-option v-for="(item, index) in inboundBusinessTypeList" :key="index" :value="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="交货方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                placeholder="请选择交货方式"
                showSearch
                optionFilterProp="children"
                v-decorator="['deliveryMethod']"
              >
                <a-select-option v-for="(item, index) in deliveryMethodList" :key="index" :value="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table
          id="billModal"
          :ref="refKeys[0]"
          :loading="materialTable.loading"
          :columns="materialTable.columns"
          :dataSource="materialTable.dataSource"
          :minWidth="minWidth"
          :maxHeight="300"
          :rowNumber="false"
          :rowSelection="rowCanEdit"
          :actionButton="rowCanEdit"
          :dragSortAndNumber="rowCanEdit"
          @valueChange="onValueChange"
          @added="onAdded"
          @deleted="onDeleted"
        />
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" label="">
              <a-textarea :rows="1" placeholder="请输入备注" v-decorator="['remark']" style="margin-top: 8px" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <vendor-modal ref="vendorModalForm" @ok="vendorModalFormOk"></vendor-modal>
    <depot-modal ref="depotModalForm" @ok="depotModalFormOk"></depot-modal>
    <batch-set-depot ref="batchSetDepotModalForm" @ok="batchSetDepotModalFormOk"></batch-set-depot>
    <import-item-modal ref="importItemModalForm" @ok="importItemModalFormOk"></import-item-modal>
    <wait-bill-list ref="waitBillList" @ok="waitBillListOk"></wait-bill-list>
    <workflow-iframe ref="modalWorkflow" @ok="workflowModalFormOk"></workflow-iframe>
    <bill-print-iframe ref="modalPrint"></bill-print-iframe>
  </j-modal>
</template>
<script>
import pick from 'lodash.pick'
import VendorModal from '../../system/modules/VendorModal'
import DepotModal from '../../system/modules/DepotModal'
import BatchSetDepot from '../dialog/BatchSetDepot'
import ImportItemModal from '../dialog/ImportItemModal'
import WorkflowIframe from '@/components/tools/WorkflowIframe'
import BillPrintIframe from '../dialog/BillPrintIframe'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { BillModalMixin } from '../mixins/BillModalMixin'
import { getMpListShort } from '@/utils/util'
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import Vue from 'vue'
import WaitBillList from '../dialog/WaitBillList'
export default {
  name: 'OtherInModal',
  mixins: [JEditableTableMixin, BillModalMixin],
  components: {
    VendorModal,
    DepotModal,
    BatchSetDepot,
    ImportItemModal,
    WaitBillList,
    WorkflowIframe,
    BillPrintIframe,
    JUpload,
    JDate,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  data() {
    return {
      title: '操作',
      width: '1600px',
      moreStatus: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      visible: false,
      operTimeStr: '',
      prefixNo: 'otherInbound',
      fileList: [],
      rowCanEdit: true,
      //出入库管理开关，适合独立仓管场景
      inOutManageFlag: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      refKeys: ['materialDataTable'],
      activeKey: 'materialDataTable',
      materialTable: {
        loading: false,
        dataSource: [],
        columns: [
          { title: '', key: 'productId', width: '1%', type: FormTypes.hidden },
          {
            title: '编号',
            key: 'productNo',
            width: '12%',
            type: FormTypes.popupJsh,
            kind: 'material',
            multi: true,
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          { title: '名称', key: 'productName', width: '10%', type: FormTypes.normal },
          { title: '规格型号', key: 'productAttributes', width: '9%', type: FormTypes.normal },
          { title: '品牌', key: 'brand', width: '6%', type: FormTypes.normal },
          { title: '单位', key: 'unit', width: '4%', type: FormTypes.normal },
          {
            title: '数量',
            key: 'quantity',
            width: '5%',
            type: FormTypes.inputNumber,
            statistics: true,
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          { title: '单价', key: 'boundPrice', width: '5%', type: FormTypes.inputNumber,  validateRules: [{ required: true, message: '${title}不能为空' }],},
          { title: '金额', key: 'boundAmount', width: '5%', type: FormTypes.inputNumber, readonly: true },
          { title: '备注', key: 'remark', width: '5%', type: FormTypes.input },
        ],
      },
      confirmLoading: false,
      validatorRules: {
        supplierId: {
          rules: [{ required: true, message: '请选择供应商!' }],
        },
        operTime: {
          rules: [{ required: true, message: '请输入单据日期!' }],
        },
        type: {
          rules: [{ required: true, message: '请选择类型!' }],
        },
        salespersonId: {
          rules: [{ required: true, message: '请选择业务员!' }],
        },
      },
      url: {
        add: '/otherInbound',
        edit: '/otherInbound/update',
        detailList: '/otherInbound/getDetailList',
      },
    }
  },
  created() {},
  methods: {
    //调用完edit()方法之后会自动调用此方法
    editAfter() {
      this.billStatus = '0'
      this.currentSelectDepotId = ''
      this.rowCanEdit = true
      this.materialTable.columns[1].type = FormTypes.popupJsh
      this.changeColumnHide()
      if (this.action === 'add') {
        this.addInit(this.prefixNo)
        this.fileList = []
      } else {
        this.model.operTime = this.model.orderDate
        this.fileList = this.model.fileName
        this.$nextTick(() => {
          this.form.setFieldsValue(
            pick(
              this.model,
              'orderNo',
              'orderDate',
              'operTime',
              'supplierId',
              'salespersonId',
              'salespersonName',
              'deliveryMethod',
              'businessType',
              'remark',
              'quantity',
              'amount'
            )
          )
        })
        this.materialTable.dataSource = this.model.inboundDetailVOList
        this.materialTable.dataSource.forEach((item, index) => {
          item.boundPrice = item.inboundPrice
          item.boundAmount = item.inboundAmount
        })
      }
      //复制新增单据-初始化单号和日期
      if (this.action === 'copyAdd') {
        this.model.id = ''
        this.model.tenantId = ''
        this.copyAddInit(this.prefixNo)
      }
      this.initSupplier(0)
      this.initUser()
      this.initInboundBusinessType()
      this.initDeliveryMethod()
    },
    //提交单据时整理成formData
    classifyIntoFormData(allValues) {
      let totalPrice = 0
      let billMain = Object.assign(this.model, allValues.formValue)
      let detailArr = allValues.tablesValue[0].values
      for (let item of detailArr) {
        item.inboundPrice = item.boundPrice
        item.inboundAmount = item.boundAmount
      }
      if (this.model.id) {
        billMain.id = this.model.id
      }
      billMain.inboundDetailDTOList = detailArr
      billMain.orderDate = billMain.operTime

      return billMain
    },
    onSearchLinkNumber() {
      this.$refs.waitBillList.show('入库', '采购,销售退货', '1,3')
      this.$refs.waitBillList.title = '请选择采购入库或销售退货'
    },
    waitBillListOk(selectBillDetailRows, linkNumber, remark) {
      this.rowCanEdit = false
      this.materialTable.columns[1].type = FormTypes.normal
      this.changeFormTypes(this.materialTable.columns, 'preNumber', 1)
      this.changeFormTypes(this.materialTable.columns, 'finishNumber', 1)
      if (selectBillDetailRows && selectBillDetailRows.length > 0) {
        let listEx = []
        for (let j = 0; j < selectBillDetailRows.length; j++) {
          let info = selectBillDetailRows[j]
          if (info.finishNumber > 0) {
            info.operNumber = info.preNumber - info.finishNumber
          }
          info.unitPrice = 0
          info.allPrice = 0
          info.linkId = info.id
          listEx.push(info)
          this.changeColumnShow(info)
        }
        this.materialTable.dataSource = listEx
        this.$nextTick(() => {
          this.form.setFieldsValue({
            linkNumber: linkNumber,
            remark: remark,
          })
        })
      }
    },
  },
}
</script>
<style scoped>
</style>